package cn.kgc.springboot.service.impl;

import cn.kgc.springboot.entity.RolePers;
import cn.kgc.springboot.mapper.RolePersMapper;
import cn.kgc.springboot.util.CodeMsg;
import cn.kgc.springboot.util.ResponseResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.springboot.entity.Permission;
import cn.kgc.springboot.service.PermissionService;
import cn.kgc.springboot.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    @Autowired(required = false)
    private RolePersMapper rolePersMapper;

    //2.查询菜单和目录
    @Override
    public ResponseResult treeSelect() {
        //权限表permission，根据条件is_menu=0(目录)或is_menu=1(菜单)查询目录和菜单
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.in("is_menu", Arrays.asList(0,1));
        List<Permission> permissions = permissionMapper.selectList(permissionQueryWrapper);

        //封装返回数据
        ResponseResult responseResult = new ResponseResult();
        responseResult.setData(permissions);
        responseResult.setMsg(CodeMsg.SELECT_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.SELECT_SUCCESS.getCode());

        return responseResult;
    }

    //6.删除操作
    @Override
    public ResponseResult deleteById(Integer id) {

        ResponseResult responseResult = new ResponseResult();
        //1.判定当前删除的权限，是否含有子菜单，有则阻止删除
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("parent_id", id);
        List<Permission> permissions = permissionMapper.selectList(permissionQueryWrapper);

        if(permissions.size()>0){
            responseResult.setMsg(CodeMsg.DELETE_FAIL.getMsg());
            responseResult.setCode(CodeMsg.DELETE_FAIL.getCode());
            return responseResult;
        }

        //2.删除权限表(permission)中的权限信息
        permissionMapper.deleteById(id);
        //3.删除角色权限关系表(role_pers)中的当前权限的信息
        QueryWrapper<RolePers> rolePersQueryWrapper = new QueryWrapper<>();
        rolePersQueryWrapper.eq("per_id",id);
        rolePersMapper.delete(rolePersQueryWrapper);

        //封装返回数据
        ResponseResult responseResult1 = new ResponseResult();
        responseResult.setMsg(CodeMsg.DELETE_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.DELETE_SUCCESS.getCode());
        return responseResult;
    }
}




